package com.zhao.fishingguideserver.service.impl;

import com.zhao.fishingguideserver.POJO.Post;
import com.zhao.fishingguideserver.POJO.PostLike;
import com.zhao.fishingguideserver.mapper.PostLikeMapper;
import com.zhao.fishingguideserver.mapper.PostMapper;
import com.zhao.fishingguideserver.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private PostLikeMapper postLikeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createPost(Post post) {
        try {
            // 设置默认值
            post.setStatus("published");
            post.setViewCount(0);
            post.setLikeCount(0);
            post.setCommentCount(0);
            post.setIsTop(false);
            post.setIsHot(false);
            post.setCreateTime(new Date());
            
            int result = postMapper.insert(post);
            return result > 0 ? "帖子发布成功" : "帖子发布失败";
        } catch (Exception e) {
            e.printStackTrace();
            return "帖子发布失败: " + e.getMessage();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updatePost(Post post) {
        try {
            int result = postMapper.updatePost(post);
            return result > 0 ? "帖子更新成功" : "帖子更新失败";
        } catch (Exception e) {
            e.printStackTrace();
            return "帖子更新失败: " + e.getMessage();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deletePost(Integer postId, Integer userId) {
        try {
            // 验证帖子是否存在且属于当前用户
            Post post = postMapper.selectById(postId);
            if (post == null) {
                return "帖子不存在";
            }
            if (!post.getUserId().equals(userId)) {
                return "无权限删除此帖子";
            }
            
            // 删除帖子（软删除，更新状态为deleted）
            post.setStatus("deleted");
            int result = postMapper.updatePost(post);
            return result > 0 ? "帖子删除成功" : "帖子删除失败";
        } catch (Exception e) {
            e.printStackTrace();
            return "帖子删除失败: " + e.getMessage();
        }
    }

    @Override
    public Post getPostById(Integer postId) {
        try {
            Post post = postMapper.selectById(postId);
            if (post != null) {
                // 增加浏览次数
                postMapper.incrementViewCount(postId);
                post.setViewCount(post.getViewCount() + 1);
            }
            return post;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Post> getPosts(Integer page, Integer size) {
        try {
            int offset = (page - 1) * size;
            return postMapper.selectPublishedPosts(offset, size);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Post> getPostsByCategory(String category, Integer page, Integer size) {
        try {
            int offset = (page - 1) * size;
            return postMapper.selectByCategory(category, offset, size);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Post> getPostsByUserId(Integer userId, Integer page, Integer size) {
        try {
            int offset = (page - 1) * size;
            return postMapper.selectByUserId(userId, offset, size);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Post> searchPosts(String keyword, Integer page, Integer size) {
        try {
            int offset = (page - 1) * size;
            return postMapper.searchPosts(keyword, offset, size);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Post> getHotPosts(Integer limit) {
        try {
            return postMapper.selectHotPosts(limit);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String toggleLike(Integer postId, Integer userId) {
        try {
            // 检查是否已点赞
            int likeCount = postLikeMapper.checkLike(postId, userId);
            
            if (likeCount > 0) {
                // 已点赞，取消点赞
                postLikeMapper.deleteByPostIdAndUserId(postId, userId);
                postMapper.updateLikeCount(postId);
                return "取消点赞成功";
            } else {
                // 未点赞，添加点赞
                PostLike postLike = new PostLike();
                postLike.setPostId(postId);
                postLike.setUserId(userId);
                postLike.setCreateTime(new Date());
                
                postLikeMapper.insert(postLike);
                postMapper.updateLikeCount(postId);
                return "点赞成功";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "点赞操作失败: " + e.getMessage();
        }
    }

    @Override
    public String incrementViewCount(Integer postId) {
        try {
            int result = postMapper.incrementViewCount(postId);
            return result > 0 ? "浏览次数更新成功" : "浏览次数更新失败";
        } catch (Exception e) {
            e.printStackTrace();
            return "浏览次数更新失败: " + e.getMessage();
        }
    }

    @Override
    public int getPostCount() {
        try {
            return postMapper.countPublishedPosts();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int getPostCountByCategory(String category) {
        try {
            return postMapper.countByCategory(category);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int getPostCountByUserId(Integer userId) {
        try {
            return postMapper.countByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
